package com.example.fengyungo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.fengyungo.R;
import com.example.fengyungo.activity.main.SearchActivity;
import com.example.fengyungo.adapter.OrderAdapter;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.constant.ResultConstant;
import com.example.fengyungo.domain.OrderDetailsVO;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;

import java.util.List;

public class MainFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = "MainFragment";

    /**
     * 刷新
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 加载中显示progressBar
     */
    ProgressBar progressBar;
    /**
     * RecyclerView
     */
    RecyclerView recyclerView;
    /**
     * LinearLayoutManager
     */
    LinearLayoutManager layoutManager;
    /**
     * OrderAdapter
     */
    OrderAdapter adapter;
    /**
     * 搜索
     */
    ImageView search;
    /**
     * 司机可接的订单
     */
    List<OrderDetailsVO> orders;


    /**
     * 引入布局，获取控件的实例
     *
     * @param inflater           LayoutInflater
     * @param container          ViewGroup
     * @param savedInstanceState Bundle
     * @return View
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        progressBar = view.findViewById(R.id.progress_bar);
        search = view.findViewById(R.id.search);

        search.setOnClickListener(this);

        recyclerView = view.findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(getActivity());

        // 获取所有可接的订单并将其通过recyclerview展示出来
        getAccessOrder(view);

        swipeRefreshLayout = view.findViewById(R.id.refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.soilyellow);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            getAccessOrder(view);
            swipeRefreshLayout.setRefreshing(false);
        });

        return view;
    }


    /**
     * 查询司机可接的订单（订单状态为未接单）
     *
     * @param view View View view = inflater.inflate(R.layout.fragment_main,container,false);
     */
    private void getAccessOrder(View view) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // 发送GET请求到后端，并接收响应数据
                    String url = DriverConstant.URL_USER_DRIVER + "/access";
                    String responseData = OkHttpUtils.get(url);

                    JSONObject jsonObject = JSONObject.parseObject(responseData);
                    String data = jsonObject.getString(ResultConstant.DATA);
                    orders = JSON.parseArray(data, OrderDetailsVO.class);
                    Log.d(TAG, "run: orders:" + orders);

                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            recyclerView.setLayoutManager(layoutManager);
                            adapter = new OrderAdapter(orders);
                            Log.d(TAG, "run: orders.size()=" + orders.size());
                            Log.d(TAG, "run: orders:" + orders);
                            recyclerView.setAdapter(adapter);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 点击对应按钮后的操作
     *
     * @param v View
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.search) {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        }
    }
}

